package com.chatplus.application.config.runner;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chatplus.application.common.event.EventPubSub;
import com.chatplus.application.common.util.ResourcesUtils;
import com.chatplus.application.dao.basedata.SensitiveWordDao;
import com.chatplus.application.domain.entity.basedata.SensitiveWordEntity;
import com.chatplus.application.domain.notification.ReloadSensitiveWordsEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 敏感词初始化
 */
@Component
@Order(1)
public class SensitiveWordInitRunner implements ApplicationRunner {

    private final EventPubSub<Serializable> eventPublisher;
    private final SensitiveWordDao sensitiveWordDao;

    @Autowired
    public SensitiveWordInitRunner(EventPubSub<Serializable> eventPublisher, SensitiveWordDao sensitiveWordDao) {
        this.eventPublisher = eventPublisher;
        this.sensitiveWordDao = sensitiveWordDao;
    }

    @Override
    public void run(ApplicationArguments args) {

        LambdaQueryWrapper<SensitiveWordEntity> queryWrapper = new LambdaQueryWrapper<>();
        long count = sensitiveWordDao.selectCount(queryWrapper);
        if (count == 0) {
            String contentString = getSensitiveSource();
            String lineSeparator = System.lineSeparator();
            String[] lines = contentString.split(lineSeparator);
            List<String> words = Arrays.stream(lines)
                    .distinct()
                    .collect(Collectors.toList());

            words.forEach(word -> {
                SensitiveWordEntity entity = new SensitiveWordEntity();
                entity.setWord(word);
                sensitiveWordDao.insert(entity);
            });

        }
        eventPublisher.publish(new ReloadSensitiveWordsEvent());
    }


    private String getSensitiveSource() {
        return ResourcesUtils.getResourceContentString("/data/sensitive_words.dict");
    }
}
